const bodyParser = require('body-parser');
const path = require('path');

let staticResource = (function () {
    let _app = null;
    let _express = null;
    let init = function (express,app) {
        /*
        * 初始化必要的参数
        * */
        _express = express;
        _app = app;
    };

    let add = function (prefix,suffix) {
        /*
        * 添加静态资源
        * prefix:挂载路径
        * suffix:资源所在文件夹
        * 在只有prefix形参的情况下,函数会认为prefix是资源路径
        * 相关介绍: http://www.expressjs.com.cn/starter/static-files.html
        * */
        try{
            if(suffix===undefined){
                _app.use(_express.static(path.resolve(prefix)));
                return 0;
            }
        }catch(err){
            console.error('position:static_resource_manage.js->add');
            console.log(err);
        }
        try{
            _app.use(prefix, _express.static(path.resolve(suffix)));
            return 0;
        } catch (err) {
            console.error('position:static_resource_manage.js->add');
            console.log(err);
        }
    };

    let defaultStaticResource = function (dist_prod) {
        /*
        * 负责管理默认加载的静态资源
        * */
        try{
            _app.use(bodyParser.json());
            _app.use(bodyParser.urlencoded({ extended: false }));
            _app.use(_express.static('img'));
            /*express会在该目录下查找一个名为index的html文件作为主页,这是他的默认行为*/
            /*详见: http://www.expressjs.com.cn/4x/api.html#express.static*/
            _app.use(_express.static(path.resolve(dist_prod)));

            _app.use('/static', _express.static(path.resolve('../spa/effect/iframeTest')));
            /*在域名后面直接添加/effect/erosion.html即可显示该网页*/
            _app.use('/effect', _express.static(path.resolve('../spa/effect/erosion/dist')));
        }catch(err){
            console.error('position:static_resource_manage.js->defaultStaticResource');
            console.error(err);
        }
    };


    return {
        init:init,
        add:add,
        defaultStaticResource:defaultStaticResource
    }

})();

module.exports = staticResource;